package com.hmyd.hmyd_android.shop;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.base.Objects;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.GoodDetails;
import com.hmyd.hmyd_android.dto.Images;
import com.hmyd.hmyd_android.dto.ShopDetailImage;
import com.hmyd.hmyd_android.fragment.ConvertRecordsFragment;
import com.hmyd.hmyd_android.ui.BasicFragmentActivity;
import com.hmyd.hmyd_android.ui.LoginActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.MySnapPageLayout;
import com.hmyd.hmyd_android.view.ViewPagerIndicator;
import com.hmyd.hmyd_android.view.ad.AutoGallery;
import com.hmyd.hmyd_android.view.ad.AutoGalleryAdapter;
import com.hmyd.hmyd_android.view.ad.AutoGalleryBase;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 商品详情
 * 
 * @author wangk
 * 
 */

@ContentView(R.layout.activity_shop_goods_details)
public class GoodsDetailsActivity extends BasicFragmentActivity implements OnClickListener,
		OnCheckedChangeListener {
	private Context mContext;

	private MySnapPageLayout mcoySnapPageLayout = null;

	private GoodsContentPage bottomPage = null;
	private GoodsDetailInfoPage topPage = null;

	private List<Fragment> mTabContents = new ArrayList<Fragment>();
	private FragmentPagerAdapter mAdapter;
	// delete  "规格参数",   2016-03-28 wangk
	private List<String> mDatas = Arrays.asList("商品详情","兑换记录");

	private ViewPagerIndicator mIndicator;
	private ViewPager mViewPager;

	private AutoGallery mHeadAd;
	private AutoGalleryAdapter mAutoGalleryAdapter;
	private ArrayList<AutoGalleryBase> mAdBase = new ArrayList<AutoGalleryBase>();

	private TextView mTvName;
	private TextView mTvOldPrice;
	private TextView mTvNewPrice;
	private TextView mTvNumber;
	private TextView mTvGoodsNum;
	private View redLine;

	@ViewInject(R.id.ib_jian)
	private Button mIBtnJian;
	private CheckBox mCheckBox;
	private Button mBtnAddToCar;
	
	@ViewInject(R.id.home_title)
	private View home_title;
	@ViewInject(R.id.home_title_txt)
	private  TextView home_title_txt;
	@ViewInject(R.id.home_left)
	private ImageView home_left;
	@ViewInject(R.layout.view_shop_detail_bottom)
	private RelativeLayout scrollPager;
	

	private int goodsNum = 1;

	// 第一个页面
	private View firstView;
	// 第二个页面
	private View secondView;

	private final int REFRESH = 1;
	private final int COLLECT = 3;
	private final int UNCOLLECT = 4;
	private boolean isFirst = true;
	private GoodDetails goodDetails;
	private String id;
	private List<GoodDetails> datas = new ArrayList<GoodDetails>();
	private SharedPreferences mySharedPreferences;
	private Editor editor;
	
	private boolean isCollection = false; // 是否收藏

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setParams();
	}

	private void onRequest() {
		if(!Objects.equal(null, id)) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", id);
			onRequest(REFRESH, UrlConstant.GOODSDETIALS, HttpMethod.GET, params);
		} else {
			finish();
		}
	}

	private void initViews() {

		mContext = this;

		mcoySnapPageLayout = (MySnapPageLayout) findViewById(R.id.flipLayout);
		firstView = getLayoutInflater().inflate(R.layout.view_shop_detail_top, null);
		secondView = getLayoutInflater().inflate(R.layout.view_shop_detail_bottom, null);
		topPage = new GoodsDetailInfoPage(GoodsDetailsActivity.this, firstView);
		bottomPage = new GoodsContentPage(GoodsDetailsActivity.this, secondView);
		mcoySnapPageLayout.setSnapPages(topPage, bottomPage);

		mTvName = (TextView) firstView.findViewById(R.id.goods_name);
		mTvNewPrice = (TextView) firstView.findViewById(R.id.tv_price);
		mTvOldPrice = (TextView) firstView.findViewById(R.id.old_price);
		mTvNumber = (TextView) firstView.findViewById(R.id.number);
		mTvGoodsNum = (TextView) findViewById(R.id.tv_goodsnum);
		redLine = firstView.findViewById(R.id.red_line);

		mBtnAddToCar = (Button) findViewById(R.id.add_to_cart);
		mBtnAddToCar.setEnabled(false);// 默认不能点击
		mCheckBox = (CheckBox) findViewById(R.id.btn_cellect);
		mCheckBox.setOnCheckedChangeListener(this);
		
		// 商品详情图文详情部分
		mViewPager = (ViewPager) findViewById(R.id.id_vp);
		mIndicator = (ViewPagerIndicator) findViewById(R.id.id_indicator);
	}

	
	@Override
	@OnClick({R.id.ji_gou,R.id.ib_jia,R.id.ib_jian,R.id.add_to_cart})
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ji_gou:
			startActivity(new Intent(mContext, JfMallShopCartActivity.class));
			break;
		case R.id.ib_jia:
			goodsNum = Integer.valueOf(mTvGoodsNum.getText().toString());

			if (goodsNum >= goodDetails.stock) {
				MyToast.showHMToast(GoodsDetailsActivity.this, false, "库存不足");
				return;
			}
			if (goodsNum >= 20) {
				MyToast.showHMToast(GoodsDetailsActivity.this, false, "您每次最多只能换购20件商品");
				return;
			}
			goodsNum = goodsNum + 1;
			mTvGoodsNum.setText(goodsNum + "");
			mIBtnJian.setEnabled(true);
			goodDetails.number = goodsNum;
			break;
		case R.id.ib_jian:
			if (goodsNum < 3) {
				mIBtnJian.setEnabled(false);
			} else {
				mIBtnJian.setEnabled(true);
			}
			goodsNum = Integer.valueOf(mTvGoodsNum.getText().toString());
			goodsNum = goodsNum - 1;
			goodDetails.number = goodsNum;
			mTvGoodsNum.setText(goodsNum + "");
			break;
		case R.id.add_to_cart:
			if (goodDetails.stock < 1) {
				MyToast.showHMToast(GoodsDetailsActivity.this, false, "库存不足");
				return;
			}
			try {
				addToCar();
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 添加到购物车
	 */
	private void addToCar() throws StreamCorruptedException, ClassNotFoundException, IOException {
		if( goodsNum<1) {
			MyToast.showHMToast(GoodsDetailsActivity.this, false, "商品数量不能小于1");
			return;
		}
		// 先获取已经添加到购物车的数据
		mySharedPreferences = getSharedPreferences("test", GoodsDetailsActivity.MODE_PRIVATE);
		editor = mySharedPreferences.edit();
		String name = mySharedPreferences.getString("data", "");
		datas.clear();
		if (TextUtils.isEmpty(name)) {// 购物车中无数据
			datas.add(goodDetails);
			List2String(datas);
		}
		String2List(name);// 购物车有数据
	}

	/**
	 * list转换成string
	 * 
	 * @param datas2
	 */
	private void List2String(List<GoodDetails> datas) throws IOException {

		// 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文件。
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 然后将得到的字符数据装载到ObjectOutputStream
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		// writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
		objectOutputStream.writeObject(datas);
		// 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
		String ListString = new String(Base64.encode(byteArrayOutputStream.toByteArray(),
				Base64.DEFAULT));
		// 关闭objectOutputStream
		objectOutputStream.close();

		// 用putString的方法保存数据
		editor.putString("data", ListString);
		editor.putInt("number", goodsNum);
		// 提交当前数据
		editor.commit();

		MyToast.showHMToast(GoodsDetailsActivity.this, true, "添加到购物车成功");
	}

	public void String2List(String ListString) throws StreamCorruptedException, IOException,
			ClassNotFoundException {
		byte[] mobileBytes = Base64.decode(ListString.getBytes(), Base64.DEFAULT);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(mobileBytes);
		ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
		@SuppressWarnings("unchecked")
		List<GoodDetails> carList = (List<GoodDetails>) objectInputStream.readObject();
		objectInputStream.close();

		String id = null;
		// 购物车中无数据直接添加
		if (carList.size() < 1) {
			datas.add(goodDetails);
			List2String(datas);
			return;
		}
		// 购物车中有数据，再判断该商品之前是否已经添加到购物车
		for (int i = 0; i < carList.size(); i++) {
			id = carList.get(i).id;
			datas.clear();
			if (goodDetails.id.equals(id)) {
				if(carList.get(i).number+goodsNum > goodDetails.stock) {
					MyToast.showHMToast(GoodsDetailsActivity.this, false,
							"购物车中已经存在该商品，\n并且商品数量已经达到最大库存");
					return;
				} 
				if (carList.get(i).number + goodsNum > 20) {
					MyToast.showHMToast(GoodsDetailsActivity.this, false,
							"购物车中已经存在该商品，\n并且您一次最多只能兑换20件商品！");
					return;
				}
				carList.get(i).number = carList.get(i).number + goodsNum;
				datas.addAll(carList);
				List2String(datas);
				return;
			}
		}
		// 如果以上都没有return掉，就会执行到这一步
		datas.addAll(carList);
		datas.add(goodDetails);
		List2String(datas);
	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case REFRESH:
			DtoInfoNoPage<GoodDetails> dtoInfoNoPage = new DtoInfoNoPage<GoodDetails>();
			Type type1 = new TypeToken<DtoInfoNoPage<GoodDetails>>() {}.getType();
			dtoInfoNoPage = gson.fromJson(result, type1);
			goodDetails = dtoInfoNoPage.data;
			setDatas();
			break;
		case COLLECT:
			mCheckBox.setText("  已收藏");
			isCollection = true; 
			MyToast.showHMToast(GoodsDetailsActivity.this, true, "收藏成功");
			break;
		case UNCOLLECT:
			mCheckBox.setText("收藏产品");
			isCollection = false; 
			MyToast.showHMToast(GoodsDetailsActivity.this, true, "取消收藏该商品");
			break;

		default:
			break;
		}

	}

	/**
	 * 设置Tab内容信息
	 */
	private void setTabContents() {
		Bundle bundle = new Bundle();
		bundle.putString("itemId", id);

		// delete 规格参数， 2016-03-28 wangk
//		ParametersFragment parametersFragment = new ParametersFragment();
//		parametersFragment.setArguments(bundle);

		ConvertRecordsFragment convertRecordsFragment = new ConvertRecordsFragment();
		convertRecordsFragment.setArguments(bundle);

		GoodsDetailFragment goodsDetailFragment = new GoodsDetailFragment();
		goodsDetailFragment.setArguments(mcoySnapPageLayout, id);

		mTabContents.add(goodsDetailFragment);
	//	mTabContents.add(parametersFragment);
		mTabContents.add(convertRecordsFragment);
		
		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
			@Override
			public int getCount() {
				return mTabContents.size();
			}

			@Override
			public Fragment getItem(int position) {
				return mTabContents.get(position);
			}
		};

		mIndicator.setTabItemTitles(mDatas);
		mViewPager.setAdapter(mAdapter);
		mIndicator.setViewPager(mViewPager, 0);
	}

	private void setDatas() {
		if (goodDetails == null) {
			return;
		}
		mBtnAddToCar.setEnabled(true);// 获取数据成功
		mTvName.setText(goodDetails.title);
		if (goodDetails.presentPrice == goodDetails.originalPrice) {
			mTvOldPrice.setVisibility(View.INVISIBLE);
			redLine.setVisibility(View.INVISIBLE);
		} else {
			mTvOldPrice.setVisibility(View.VISIBLE);
			redLine.setVisibility(View.VISIBLE);
		}
		mTvNewPrice.setText(goodDetails.presentPrice + "");
		mTvOldPrice.setText(goodDetails.originalPrice + "");
		if (goodDetails.stock >= 999) {
			mTvNumber.setText("放心购");
		} else {
			mTvNumber.setText(goodDetails.stock + "");
		}
		if (goodDetails.isCollected) {
			mCheckBox.setChecked(true);
			mCheckBox.setText("  已收藏");
		} else {
			isFirst = false;
		}
		goodDetails.number = goodsNum;
		if(mAdBase!=null) {
			mAdBase.clear();
		}
		for (int i = 0; i < goodDetails.icon.size(); i++) {
			AutoGalleryBase itemBase = new AutoGalleryBase();
			itemBase.mUrl = goodDetails.icon.get(i);
			mAdBase.add(itemBase);
		}

		// 详情图片滚动
		View view = findViewById(R.id.flayout);
		mHeadAd = (AutoGallery) findViewById(R.id.Gallery);
		mAutoGalleryAdapter = new AutoGalleryAdapter(GoodsDetailsActivity.this, mHeadAd, mAdBase);
		mHeadAd.setAdapter(mAutoGalleryAdapter);
		mHeadAd.initPointView(GoodsDetailsActivity.this, view);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (!AppBasic.isLogin) {
			startActivity(new Intent(mContext, LoginActivity.class));
			return;
		}
		RequestParams params = new RequestParams();
		if (isChecked) {
			if (isFirst) {
				isFirst = false;
				return;
			}
			params.addBodyParameter("itemId", id);
			params.addBodyParameter("isCollection", "true");
			onRequest(COLLECT, UrlConstant.COLLECT, HttpMethod.POST, params);
		} else {
			isFirst = false;
			params.addBodyParameter("itemId", id);
			params.addBodyParameter("isCollection", "false");
			onRequest(UNCOLLECT, UrlConstant.COLLECT, HttpMethod.POST, params);
		}
	}

	
	
	public void setParams() {
		initViews();
		home_title_txt.setText("商品详情");
		home_title.setOnTouchListener(touch);
		id = getIntent().getStringExtra("id");
		// 获取id失败，直接结束activity
		if(TextUtils.isEmpty(id)) {
			AppBasic.getInstance().finishCurrentActivity();
			return;
		}

		onRequest();

		setTabContents();
	}

	@Override
	protected void onResume() {
		mViewPager.invalidate();
		mIndicator.invalidate();
		if(mcoySnapPageLayout != null) {
			mcoySnapPageLayout.invalidate();
		}
		super.onResume();
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			requestCallbackParam();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 发送广播，通知收藏
	 */
	private void requestCallbackParam() {
			Intent intent = new Intent();
			intent.setAction("collected");
			intent.putExtra("id", id);
			intent.putExtra("isCollection", isCollection);
			sendBroadcast(intent);
			AppBasic.getInstance().finishCurrentActivity();
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onPostFailure(int postId, String msg) {
	}
	
	/**
	 * 添加 Home Title 触摸监听事件（必须要添加在子类中）
	 */
	protected OnTouchListener touch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int X = (int) event.getX();
			if (X < Utils.screenWidth_ / 5) {
				leftButton();
			} else if (X > Utils.screenWidth_ * 4 / 5) {
				rightButton();
			}
			return false;
		}
	};

	/**
	 * Home Title 左侧触摸事件调用方法
	 */
	protected void leftButton() {
		requestCallbackParam();
	};

	/**
	 * Home Title 右侧触摸事件调用方法
	 */
	protected void rightButton() {
	};

}
